from typing import Dict, List

from config.logging_config import get_logger

logger = get_logger(__name__)


class ToolsUtils:
    """工具相关的通用方法集合"""

    @staticmethod
    def build_context_info(tool_results: List[Dict] = None, rag_results: List[Dict] = None,
                           mcp_results: List[Dict] = None) -> str:
        """构建上下文信息的通用方法"""
        context_info = []

        if tool_results:
            context_info.append("工具执行结果：")
            for result in tool_results:
                if result.get("success"):
                    context_info.append(f"- {result['tool_name']}: {result['result']}")
                else:
                    context_info.append(f"- {result['tool_name']}: 执行失败 - {result.get('error', '未知错误')}")

        if rag_results:
            context_info.append("知识库检索结果：")
            for result in rag_results:
                if "content" in result:
                    context_info.append(f"- {result['content']}")

        if mcp_results:
            context_info.append("MCP接口结果：")
            for result in mcp_results:
                if result.get("success"):
                    context_info.append(f"- {result['mcp_name']}: {result['result']}")

        return "\n".join(context_info) if context_info else "无额外信息"

    @staticmethod
    def validate_tool_result(result: Dict) -> bool:
        """验证工具执行结果的格式"""
        required_fields = ['tool_name', 'success']
        return all(field in result for field in required_fields)

    @staticmethod
    def format_tool_error(tool_name: str, error: str) -> Dict:
        """格式化工具错误信息"""
        return {
            "tool_name": tool_name,
            "success": False,
            "error": error,
            "result": None
        }

    @staticmethod
    def format_tool_success(tool_name: str, result: any) -> Dict:
        """格式化工具成功结果"""
        return {
            "tool_name": tool_name,
            "success": True,
            "error": None,
            "result": result
        }
